<template>
  <div class="container">
    <div class="top">
      <div>
        <span>
          <span>年度：&nbsp;&nbsp;</span>
          <el-date-picker v-model="searchData.year" type="year" value-format="YYYY" />
        </span>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <el-button type="primary" plain @click="search">查询</el-button>
        <el-button type="primary" plain @click="resetSearch">重置</el-button>
      </div>
      <div>
        <el-button type="primary" @click="handleImport">导入</el-button>
        <el-button type="primary" @click="handleExport">导出</el-button>
        <el-button type="primary" @click="add">新增</el-button>
      </div>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" height="calc(100% - 20px)">
      <el-table-column type="index" label="序号" width="55"> </el-table-column>
      <el-table-column prop="year" label="年度"> </el-table-column>
      <el-table-column prop="lineType" label="线别"> </el-table-column>
      <el-table-column prop="interval" label="区间"> </el-table-column>
      <el-table-column prop="mileage" label="起讫里程"> </el-table-column>
      <el-table-column prop="stream" label="行别"> </el-table-column>
      <el-table-column prop="type" label="类别"> </el-table-column>
      <el-table-column prop="situation" label="预计可能发生水害情况"> </el-table-column>
      <el-table-column label="预防措施">
        <el-table-column prop="tool" label="抢险料具" width="100"> </el-table-column>
        <el-table-column prop="number" label="抢险人数"> </el-table-column>
        <el-table-column prop="system" label="观测制度"> </el-table-column>
        <el-table-column prop="method" label="抢险办法" width="200"> </el-table-column>
      </el-table-column>
      <el-table-column prop="deptName" label="所属工区"> </el-table-column>
      <el-table-column prop="head" label="责任人"> </el-table-column>
      <el-table-column prop="cadre" label="包保干部"> </el-table-column>
      <el-table-column prop="level" label="级别"> </el-table-column>
      <el-table-column prop="grade" label="分级"> </el-table-column>
      <el-table-column prop="date" label="是否已列整治计划">
        <template #default="scope">
          {{ scope.row.isRepairPlan == 0 ? "否" : "是" }}
        </template>
      </el-table-column>
      <el-table-column prop="date" label="防洪警示标志">
        <template #default="scope">
          <el-icon title="防洪警示标志" @click="jump(scope.row)">
            <Edit />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="操作" width="100px">
        <template #default="scope">
          <el-icon title="编辑" @click="edit(scope.row)">
            <Edit />
          </el-icon>
          &nbsp;
          <el-icon title="删除" @click="del(scope.row)">
            <Delete />
          </el-icon>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog title="重点防洪地段详情" v-model="open" width="1090px" append-to-body>
      <el-form ref="postRef" :inline="true" :model="form" class="demo-form-inline" label-width="80px">
        <el-form-item label="年度">
          <el-date-picker v-model="form.year" type="year" value-format="YYYY" />
        </el-form-item>
        <el-form-item label="线别">
          <el-input v-model="form.lineType" />
        </el-form-item>
        <el-form-item label="区间">
          <el-input v-model="form.interval" />
        </el-form-item>
        <el-form-item label="起讫里程">
          <!-- <el-input v-model="form.mileage" /> -->
          K<el-input-number v-model="numOne" :min="0" :controls="false" style="width: 60px;" />
          +<el-input-number v-model="numTwo" :min="0" :controls="false" style="width: 60px;" />-
          K<el-input-number v-model="numThree" :min="0" :controls="false" style="width: 60px;" />
          +<el-input-number v-model="numFour" :min="0" :controls="false" style="width: 60px;" />
        </el-form-item>
        <el-form-item label="行别">
          <el-select v-model="form.stream" placeholder="请选择">
            <el-option label="上行" value="上行" />
            <el-option label="下行" value="下行" />
            <el-option label="上下行" value="上下行" />
          </el-select>
        </el-form-item>
        <el-form-item label="类别">
          <el-input v-model="form.type" />
        </el-form-item>
        <el-form-item label="预计可能发生水害情况" label-width="auto" style="width: 96%;">
          <el-input v-model="form.situation" />
        </el-form-item>
        <div style="display: flex;">
          <div style="width: 20%;text-align: center;line-height: 12;">预防措施</div>
          <div style="display: flex;flex-direction: column;">
            <el-form-item label="抢险料具" label-width="auto">
              <el-input v-model="form.tool" style="width: 660px;" />
            </el-form-item>
            <el-form-item label="抢险人数" label-width="auto">
              <el-input-number v-model="form.number" :step="1" :min="0" :precision="0" style="width: 660px;" />
            </el-form-item>
            <el-form-item label="观测制度" label-width="auto">
              <el-input v-model="form.system" style="width: 660px;" />
            </el-form-item>
            <el-form-item label="抢险办法" label-width="auto">
              <el-input type="textarea" v-model="form.method" style="width: 660px;" />
            </el-form-item>
          </div>
        </div>
        <div style="display: flex;">
          <el-form-item label="所属工区">
            <el-tree-select v-model="form.workAreaId" :data="dataSource"
              :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" :render-after-expand="false"
              check-strictly @change="treeChange">
            </el-tree-select>
          </el-form-item>
          <el-form-item label="责任人">
            <el-select v-model="form.headIds" placeholder="请选择" multiple collapse-tags>
              <el-option v-for="item in options" :key="item.userId" :label="item.userName" :value="item.userId" />
            </el-select>
          </el-form-item>
          <el-form-item label="包保干部">
            <el-select v-model="form.cadreIds" placeholder="请选择" multiple collapse-tags>
              <el-option v-for="item in BBGBoptions" :key="item.userId" :label="item.userName" :value="item.userId" />
            </el-select>
          </el-form-item>
          <el-form-item label="级别">
            <!-- <el-input-number v-model="form.level" :step="1" :min="1" :max="3" :precision="0" /> -->
            <el-select v-model="form.level">
              <el-option label="I" value="I" />
              <el-option label="II" value="II" />
              <el-option label="III" value="III" />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="是否已列整治计划" label-width="auto">
          <!-- <el-select v-model="form.isRepairPlan">
            <el-option label="否" :value="0" />
            <el-option label="是" :value="1" />
          </el-select> -->
          <el-input v-model="form.isRepairPlan" />
        </el-form-item>
        <el-form-item label="分级" label-width="auto">
          <el-select v-model="form.grade">
            <el-option label="准池级" value="准池级"/>
            <el-option label="新朔级" value="新朔级" />
          </el-select>
        </el-form-item>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :data="{ withWarning: 1 }"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ElMessage,
  ElMessageBox
} from 'element-plus'
import {
  getControl,
  delControl,
  addControl,
  editControl,
  getTreeList,
  getPersonBy,
  getDept
} from "@/api/work";
const {
  proxy
} = getCurrentInstance();
const dataSource = ref([])

function getTree() {
  getTreeList().then(res => {
    dataSource.value = res.data
  })
}
getTree()
const options = ref([])
const BBGBoptions = ref([])

const all = ref([])

const parentId = ref("")


function treeChange(id) {
  getPersonBy({
    deptId: id
  }).then(res => {
    all.value = JSON.parse(JSON.stringify(res.rows))
    options.value = res.rows
    form.value.headId = ""
    form.value.cadreId = ""
    form.value.headIds = []
    form.value.cadreIds = []
    changeCadreIds(id)
  })
}

const numOne = ref(0)
const numTwo = ref(0)
const numThree = ref(0)
const numFour = ref(0)
const open = ref(false)
const searchData = ref({
  year: '',
})

function search() {
  getControl(searchData.value).then(res => {
    tableData.value = res.rows
  })
}

function resetSearch() {
  searchData.value = {
    year: '',
  }
  getList()
}
const tableData = ref([])
const loading = ref(true);

function getList() {
  loading.value = true
  getControl().then(res => {
    tableData.value = res.rows
    loading.value = false
  })
}
getList()


function add() {
  numOne.value = 0
  numTwo.value = 0
  numThree.value = 0
  numFour.value = 0
  open.value = true
  form.value = {}
  form.value.cadreIds = []
  form.value.headIds = []
  options.value = []
}
import { getToken } from '@/utils/auth'
/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken(), withWarning: "1" },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/sjgtw-emergency/keysAreas/importData',
})
/** 导入按钮操作 */
function handleImport() {
  upload.title = '导入'
  upload.open = true
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs['uploadRef'].submit()
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download('sjgtw-emergency/keysAreas/downloadTemplate?withWarning=1', {}, `template_${new Date().getTime()}.xlsx`)
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs['uploadRef'].handleRemove(file)
  if (response.code == 200) {
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
  } else {
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + '</div>', '导入失败', { dangerouslyUseHTMLString: true })
  }
  getList()
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download("sjgtw-emergency/keysAreas/export?withWarning=1", {
    ...queryParams.value,
  }, `防洪重点地段管理${new Date().getTime()}.xlsx`);
}

function edit(data) {
  let row = JSON.parse(JSON.stringify(data))
  let str = row.mileage
  str = str.replaceAll("K", "")
  str = str.replaceAll("+", ",")
  str = str.replaceAll("-", ",")
  console.log(str)
  str = str.split(",")
  numOne.value = str[0]*1
  numTwo.value = str[1]*1
  numThree.value = str[2]*1
  numFour.value = str[3]*1
  row.number = row.number * 1
  form.value = row
  console.log(row, "row")
  if(row.cadreId && row.cadreId!=""){
    form.value.cadreIds = (row.cadreId).split(",")
  }else{
    form.value.cadreIds = []
  }
  if(row.headId && row.headId!=""){
    form.value.headIds = (row.headId).split(",")
  }else{
    form.value.headIds = []
  }
  // form.value.headIds = (row.headId + "").split(",") || []

  if (form.value.cadreIds.length) {
    form.value.cadreIds = form.value.cadreIds.map(item => item * 1)
  }
  if (form.value.headIds.length) {
    form.value.headIds = form.value.headIds.map(item => item * 1)
  }
  getPersonBy({
    deptId: row.workAreaId
  }).then(res => {
    all.value = JSON.parse(JSON.stringify(res.rows))
    options.value = res.rows
  })
  changeCadreIds(row.workAreaId)
  open.value = true
}

function del(data) {
  ElMessageBox.confirm(
    '确认删除吗？',
    'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }
  )
    .then(() => {
      delControl(data.id).then(res => {
        ElMessage({
          type: 'success',
          message: '已删除',
        })
        getList()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const router = useRouter();
function jump(data) {
  router.push({ name: 'Sign', query: { keysAreasId: data.id } })
}

function cancel() {
  open.value = false
}

function submitForm() {
  if (numOne.value == null || numOne.value == undefined) {
    numOne.value = 0
  }
  if (numTwo.value == null || numTwo.value == undefined) {
    numTwo.value = 0
  }
  if (numThree.value == null || numThree.value == undefined) {
    numThree.value = 0
  }
  if (numFour.value == null || numFour.value == undefined) {
    numFour.value = 0
  }
  form.value.mileage = `K${numOne.value}+${numTwo.value}-K${numThree.value}+${numFour.value}`
  form.value.cadreId = form.value.cadreIds.join(",") || ""
  form.value.headId = form.value.headIds.join(",") || ""
  if (form.value.headIds.length == 0) {
    form.value.headIds = ""
  }
  if (form.value.cadreIds.length == 0) {
    form.value.cadreId = ""
  }

  proxy.$refs["postRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        editControl(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList()
        });
      } else {
        addControl(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList()
        });
      }
    }
  });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    postCode: undefined,
    postName: undefined,
    phone: undefined
  },
  rules: {
    leaderPhone: [{
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }],
    assistantPhone: [{
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }],
  }
});
const {
  queryParams,
  form,
  rules
} = toRefs(data);

function changeCadreIds(id) {
  getDept(id).then(res => {
    parentId.value = res.data.parentId
    if (parentId.value == 0) { // 顶级部门
      BBGBoptions.value = []
      return
    }
    getPersonBy({
      deptId: parentId.value
    }).then(res => {
      // all.value = JSON.parse(JSON.stringify(res.rows))
      BBGBoptions.value = res.rows
      // form.value.headId = ""
      // form.value.cadreId = ""
    })
  })
}
</script>

<style lang='scss' scoped>
.container {
  height: 100%;
  width: 100%;
  padding: 20px;
}

.top {
  height: 40px;
  line-height: 40px;
  display: flex;
  justify-content: space-between;
}

.end {
  justify-content: flex-end;
}

:deep(.el-table .el-table__cell) {
  text-align: center;
}

:deep(.el-table--border::before) {
  width: 0px;
  ;
}

:deep(.el-table--border::after) {
  width: 0px;
  ;
}
</style>